from flask import Flask, render_template, request, jsonify, send_file
import requests
import pandas as pd
import json
import io
from datetime import datetime
import plotly.express as px
import plotly.graph_objects as go
from plotly.utils import PlotlyJSONEncoder

app = Flask(__name__)

# 配置
app.config['SECRET_KEY'] = 'agricultural_system_2024'
app.config['EXTERNAL_SYSTEM_URL'] = 'http://192.168.43.230:8080/'
app.config['API_BASE_URL'] = 'http://192.168.43.230:8080/api'

# 模拟数据 - 在实际项目中这些数据会从API获取
MOCK_DATA = {
    'prod_categories': ['蔬菜', '水果', '粮食', '油料'],
    'products': ['苹果', '西红柿', '大米', '玉米', '土豆', '白菜'],
    'table_data': [
        {
            'prodCat': '蔬菜',
            'prodPcat': '叶菜类',
            'prodName': '白菜',
            'lowPrice': 2.5,
            'avgPrice': 3.2,
            'highPrice': 4.0,
            'specInfo': '500g/袋',
            'place': '山东',
            'unitInfo': '元/斤',
            'pubDate': '2024-01-15'
        },
        {
            'prodCat': '水果',
            'prodPcat': '核果类',
            'prodName': '苹果',
            'lowPrice': 4.5,
            'avgPrice': 5.8,
            'highPrice': 7.2,
            'specInfo': '1kg/袋',
            'place': '陕西',
            'unitInfo': '元/斤',
            'pubDate': '2024-01-15'
        },
        {
            'prodCat': '粮食',
            'prodPcat': '谷物类',
            'prodName': '大米',
            'lowPrice': 2.8,
            'avgPrice': 3.5,
            'highPrice': 4.2,
            'specInfo': '5kg/袋',
            'place': '黑龙江',
            'unitInfo': '元/斤',
            'pubDate': '2024-01-15'
        }
    ]
}

def get_api_data(endpoint, params=None):
    """从API获取数据"""
    try:
        url = f"{app.config['API_BASE_URL']}/{endpoint}"
        response = requests.get(url, params=params, timeout=5)
        if response.status_code == 200:
            return response.json()
        else:
            return None
    except:
        return None

def create_price_chart(data, title, chart_type='line'):
    """创建价格图表"""
    if chart_type == 'line':
        fig = px.line(data, x='time', y='price', title=title,
                     color_discrete_sequence=['#2d5016'])
    elif chart_type == 'bar':
        fig = px.bar(data, x='type', y='value', title=title,
                    color_discrete_sequence=['#2d5016'])
    
    fig.update_layout(
        plot_bgcolor='white',
        paper_bgcolor='white',
        font=dict(color='#2d5016'),
        title_font_color='#2d5016'
    )
    return json.dumps(fig, cls=PlotlyJSONEncoder)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/data_search')
def data_search():
    """数据搜索页面"""
    return render_template('data_search.html', 
                         categories=MOCK_DATA['prod_categories'])

@app.route('/api/data/search')
def api_data_search():
    """数据搜索API"""
    page = int(request.args.get('page', 1))
    size = int(request.args.get('size', 20))
    prod_cat = request.args.get('prodCat', '')
    prod_name = request.args.get('prodName', '')
    
    # 过滤数据
    filtered_data = MOCK_DATA['table_data']
    if prod_cat:
        filtered_data = [item for item in filtered_data if item['prodCat'] == prod_cat]
    if prod_name:
        filtered_data = [item for item in filtered_data if prod_name.lower() in item['prodName'].lower()]
    
    # 分页
    start = (page - 1) * size
    end = start + size
    paginated_data = filtered_data[start:end]
    
    return jsonify({
        'code': 200,
        'message': '查询成功',
        'data': {
            'records': paginated_data,
            'total': len(filtered_data),
            'pageNum': page,
            'pageSize': size
        }
    })

@app.route('/api/data/categories')
def api_categories():
    """获取产品分类"""
    return jsonify({
        'code': 200,
        'data': MOCK_DATA['prod_categories']
    })

@app.route('/export_excel')
def export_excel():
    """导出Excel"""
    try:
        # 获取搜索参数
        prod_cat = request.args.get('prodCat', '')
        prod_name = request.args.get('prodName', '')
        
        # 过滤数据
        filtered_data = MOCK_DATA['table_data']
        if prod_cat:
            filtered_data = [item for item in filtered_data if item['prodCat'] == prod_cat]
        if prod_name:
            filtered_data = [item for item in filtered_data if prod_name.lower() in item['prodName'].lower()]
        
        # 创建DataFrame
        df = pd.DataFrame(filtered_data)
        
        # 创建Excel文件
        output = io.BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            df.to_excel(writer, sheet_name='农产品数据', index=False)
        
        output.seek(0)
        
        filename = f'农产品数据_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xlsx'
        return send_file(
            output,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/price_distribution')
def price_distribution():
    """价格分布页面"""
    return render_template('price_distribution.html')

@app.route('/api/price_distribution')
def api_price_distribution():
    """价格分布数据"""
    product = request.args.get('product', '苹果')
    granularity = request.args.get('granularity', 'month')
    
    # 模拟数据
    data = {
        '苹果': {
            'month': [
                {'time': '2024-01', 'price': 5.2},
                {'time': '2024-02', 'price': 5.5},
                {'time': '2024-03', 'price': 5.8},
                {'time': '2024-04', 'price': 6.0},
                {'time': '2024-05', 'price': 6.2}
            ]
        }
    }
    
    chart_data = data.get(product, {}).get(granularity, [])
    chart_json = create_price_chart(chart_data, f'{product}价格分布')
    
    return jsonify({
        'code': 200,
        'data': chart_data,
        'chart': chart_json
    })

@app.route('/price_statistics')
def price_statistics():
    """价格统计页面"""
    return render_template('price_statistics.html')

@app.route('/api/price_statistics')
def api_price_statistics():
    """价格统计数据"""
    stat_type = request.args.get('type', 'avg')
    
    # 模拟数据
    data = {
        'avg': [
            {'type': '蔬菜', 'value': 3.5},
            {'type': '水果', 'value': 5.2},
            {'type': '粮食', 'value': 2.8},
            {'type': '油料', 'value': 4.1}
        ]
    }
    
    chart_data = data.get(stat_type, [])
    chart_json = create_price_chart(chart_data, '农产品价格统计', 'bar')
    
    return jsonify({
        'code': 200,
        'data': chart_data,
        'chart': chart_json
    })

@app.route('/price_prediction')
def price_prediction():
    """价格预测页面"""
    return render_template('price_prediction.html')

@app.route('/api/price_prediction')
def api_price_prediction():
    """价格预测数据"""
    product_type = request.args.get('type', '蔬菜')
    days = int(request.args.get('days', 7))
    
    # 模拟历史数据和预测数据
    history_data = [3.2, 3.5, 3.8, 4.0, 4.2, 4.3, 4.5]
    predict_data = [4.6, 4.7, 4.8, 4.9, 5.0, 5.1, 5.2]
    
    # 创建双线图
    fig = go.Figure()
    
    # 历史数据
    fig.add_trace(go.Scatter(
        x=list(range(len(history_data))),
        y=history_data,
        mode='lines+markers',
        name='历史价格',
        line=dict(color='#2d5016', width=3)
    ))
    
    # 预测数据
    fig.add_trace(go.Scatter(
        x=list(range(len(history_data), len(history_data) + len(predict_data))),
        y=predict_data,
        mode='lines+markers',
        name='预测价格',
        line=dict(color='#8b4513', width=3, dash='dash')
    ))
    
    fig.update_layout(
        title=f'{product_type}价格预测',
        plot_bgcolor='white',
        paper_bgcolor='white',
        font=dict(color='#2d5016'),
        title_font_color='#2d5016'
    )
    
    return jsonify({
        'code': 200,
        'chart': json.dumps(fig, cls=PlotlyJSONEncoder)
    })

@app.route('/recent_prices')
def recent_prices():
    """近日均价页面"""
    return render_template('recent_prices.html')

@app.route('/api/recent_prices')
def api_recent_prices():
    """近日均价数据"""
    product_type = request.args.get('type', '蔬菜')
    days = int(request.args.get('days', 7))
    
    # 模拟数据
    prices = [3.2, 3.5, 3.8, 4.0, 4.2, 4.3, 4.5]
    data = [{'time': f'第{i+1}天', 'price': price} for i, price in enumerate(prices[:days])]
    
    chart_json = create_price_chart(data, f'{product_type}近日均价')
    
    return jsonify({
        'code': 200,
        'data': data,
        'chart': chart_json
    })

@app.route('/external_system')
def external_system():
    """外部系统跳转页面"""
    return render_template('external_system.html')

@app.route('/api/check_external_system')
def api_check_external_system():
    """检查外部系统状态"""
    try:
        response = requests.get(app.config['EXTERNAL_SYSTEM_URL'], timeout=3)
        accessible = response.status_code == 200
    except:
        accessible = False
    
    return jsonify({
        'code': 200,
        'accessible': accessible
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000) 